import { defineStore } from "pinia";
import request from "@/utils/request";
const formData = new FormData();
if(localStorage.getItem("userInfo")){
  formData.append("userId", JSON.parse(localStorage.getItem("userInfo")).id)

}

export const useMessageStore = defineStore("message", {
  state: () => ({
    messages: [],
    friends: [],
    currentChatId: null,
    isRecording: false,
    emojiList: [
      "😊",
      "😂",
      "🤔",
      "❤️",
      "👍",
      "🎉",
      "🌟",
      "💕",
      "😍",
      "😭",
      "😅",
      "😆",
      "😉",
      "😋",
      "😎",
      "😡",
      "😢",
      "😣",
      "😤",
      "😥",
      "😦",
      "😧",
      "😨",
      "😩",
      "😪",
      "😫",
      "😬",
      "😭",
      "😮",
      "😯",
      "😰",
      "😱",
      "😲",
      "😳",
      "😴",
      "😵",
      "😶",
      "😷",
      "😸",
      "😹",
      "😺",
      "😻",
      "😼",
      "😽",
      "😾",
      "😿",
      "🙀",
      "🙁",
      "🙂",
      "🙃",
      "🙄",
      "🙅",
      "🙆",
      "🙇",
      "🙈",
      "🙉",
      "🙊",
      "🙋",
      "🙌",
      "🙍",
      "🙎",
      "🙏",
    ],
    unreadCount: 0,
  }),

  actions: {
    async getMessages(chatId) {
      try {
        const response = await request({
          url: "/api/messages",
          method: "post",
          data: formData,
          headers: {
            "Content-Type": "multipart/form-data", // 必须设置
          },
        });

        this.friends = response.friends;
      } catch (error) {
        console.error("获取聊天记录失败:", error);
      }
    },

    // 获取聊天记录
    async getChatHistory(chatId) {
      const formData = new FormData();
      formData.append("userId2", chatId.userId2);
      formData.append("userId1",  chatId.userId1)
      try {
         await request({
          url: `/api/chat/history`,
          method: "post",
          data: formData,
          headers: {
            "Content-Type": "multipart/form-data", // 必须设置
          },
        });
      } catch (error) {
        console.error("获取聊天记录失败:", error);
      }
    },

    // 发送文本消息
    async sendTextMessage(data) {
      console.log(data);
      const formData = new FormData();
      formData.append("receiverId", data.receiverId.value);
      formData.append("type", "text");
      formData.append("content", data.content);
      formData.append(
        "senderId",
        JSON.parse(localStorage.getItem("userInfo")).id
      );
      try {
        await request({
          url: "/api/chat/send",
          method: "post",
          data: formData,
          headers: {
            "Content-Type": "multipart/form-data", // 必须设置
          },
        });
        if (true) {
          this.messages.push(data.content);
        }
      } catch (error) {
        console.error("发送消息失败:", error);
      }
    },

    // 发送语音消息
    async sendVoiceMessage(audioBlob) {
      try {
        const formData = new FormData();
        formData.append("receiverId", audioBlob.receiverId);
        formData.append("type", "voice");
        formData.append(
          "senderId",
          JSON.parse(localStorage.getItem("userInfo")).id
        );
        formData.append("voiceFile", audioBlob.voiceFile);
        formData.append("duration", audioBlob.duration);

        await request.post("/api/chat/send", formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        });
      } catch (error) {
        console.error("发送语音消息失败:", error);
      }
    },

    // 发送表情消息
    async sendEmoji(data) {
      console.log(data);
      const formData = new FormData();
      formData.append("receiverId", data.receiverId);
      formData.append("type", "emoji");
      formData.append("emojiCode", data.content);
      formData.append(
        "senderId",
        JSON.parse(localStorage.getItem("userInfo")).id
      );
      try {
        const response1 = await request({
          url: "/api/chat/send",
          method: "post",
          data: formData,
          headers: {
            "Content-Type": "multipart/form-data", // 必须设置
          },
        });
      } catch (error) {
        console.error("发送消息失败:", error);
      }
    },

    // 开始录音
    startRecording() {
      this.isRecording = true;
    },

    // 停止录音
    stopRecording() {
      this.isRecording = false;
    },

    // 获取未读消息数
    async getUnreadCount() {
      try {
        const response = await request.get("/api/chat/unread-count");
        if (response.data.success) {
          this.unreadCount = response.data.count;
        }
      } catch (error) {
        console.error("获取未读消息数失败:", error);
      }
    },

    // 标记消息为已读
    async markAsRead(chatId) {
      try {
        await request.post(`/api/chat/mark-read/${chatId}`);
        this.unreadCount = Math.max(0, this.unreadCount - 1);
      } catch (error) {
        console.error("标记消息已读失败:", error);
      }
    },
  },
});
